﻿Imports System.Net
Imports System.IO
Imports System.Runtime.Serialization.Json

Public Class SitemapTranslator

    Public Shared Function Translate(ByVal strToTranslate As String, ByVal language As String) As String
        'using mymemory api (http://mymemory.translated.net/doc/spec.php)
        'Format: http://mymemory.translated.net/api/get?q=string-to-translate&langpair=original-language|translation-language

        Dim UrlString As String = String.Format("http://mymemory.translated.net/api/get?q={0}&langpair={1}|{2}", strToTranslate, Storage.OriginalLanguage, language)
        Dim translatedString As String = strToTranslate

        'If language <> Storage.OriginalLanguage Then
        If language <> "it" Then
            Dim response As HttpWebResponse

            Try
                Dim webRequest As HttpWebRequest = DirectCast(System.Net.WebRequest.Create(UrlString), HttpWebRequest)
                webRequest.Method = "GET"

                response = DirectCast(webRequest.GetResponse(), HttpWebResponse)                
                Dim jsonSerializer As DataContractJsonSerializer = New DataContractJsonSerializer(GetType(TranslationData))
                Dim translation As TranslationData = CType(jsonSerializer.ReadObject(response.GetResponseStream()), TranslationData)

                translatedString = translation.responseData.translatedText
            Catch ex As Exception
            Finally
                If Not response Is Nothing Then response.Close()
            End Try
        End If

        Return translatedString
    End Function

End Class
